package epam.car.rent.web.tags;

import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Locale;
import java.util.ResourceBundle;

/**
 * Custom tag that outputs a language switch panel
 * @author Alexander Tretyak
 *
 */
public class LangSwitch extends TagSupport {

    private static final Logger log = Logger.getLogger("carrentlogger");

	@Override
    public int doStartTag() throws JspException {
    	HttpSession session = (HttpSession) pageContext.getSession();
    	JspWriter w = pageContext.getOut();

    	// setting english as default language
    	
    	if(session.getAttribute("myLocale")==null){
    		Locale locale = null;
    		locale = new Locale("en", "EN");
    		session.setAttribute("myLocale", locale);
    		ResourceBundle bundle = ResourceBundle.getBundle("/i18n/crBundle", locale);
    		for (Enumeration e = bundle.getKeys(); e.hasMoreElements();) {
    			String key = (String) e.nextElement();
    			String s = bundle.getString(key);
    			session.setAttribute(key, s);
    		}
    	}
    	
    	//building a language panel
    	
    	try {
			w.write("<div id=\"languagePanel\">");
			w.write("<form action=\""+pageContext.getServletContext().getContextPath()+"/SetLang\" method=\"get\">");
			w.write("<input type=\"radio\" name=\"lang\" value=\"Russian\">Russian</input>");
			w.write("<input type=\"radio\" name=\"lang\" value=\"Ukrainian\">Ukrainian</input>");
			w.write("<input type=\"radio\" name=\"lang\" value=\"English\">English</input>");
			w.write("<input type=\"submit\" value=\"ok\"/>");
			w.write("</form></div>");
		} catch (IOException e) {
			log.warn(e.getMessage());
		}
    	return SKIP_BODY;
    }

    @Override
    public int doEndTag() throws JspException {
        return EVAL_PAGE;
    }
}
